# coding=utf-8
from flask import Flask, Blueprint
from datetime import datetime
from utils import restful

from .common import queryUserCache, seckill_script
from setting import Prefixs
from decorator import login_required
from utils.redis import Redis

from utils.ID_Creator import snow_id_creator

import time

bp = Blueprint("voucher-order", __name__, url_prefix="/voucher-order")


@bp.route("/seckill/<int:id>", methods=["POST"])
@login_required
def seckill(id):
    user_info = queryUserCache()  # 拿到用户信息
    order_id = snow_id_creator(Prefixs.incr_voucher_orderId_prefix)  # 创建订单唯一id
    # 使用lua脚本判断用户是否有资格下订单
    flag = Redis.register_script(seckill_script, keys=[order_id],
                                 args=[Prefixs.seckill_voucher_stock_prefix, id, Prefixs.voucherIdPrefix_with_userIdSet,
                                       user_info['id'], datetime.now().strftime('%Y-%m-%d %H:%M:%S')])
    messages = {1: "活动还未开始！", 2: "活动已经结束！", 3: "优惠券已经被抢完啦！", 4: "订单已存在！"}
    if flag != 0:
        return restful.fail(messages[flag])
    return restful.success(data=order_id)
